﻿namespace BEGDC.CC.Web.UserControls.EBD
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Collections;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.EBD;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.UserManagement;
    using BEGDC.CC.BL.Common.Query;

    /// <summary>
    ///		Summary description for AssignApp.
    /// </summary>
    public class AssignApp : BaseEBD
    {
        #region Variables
        protected System.Web.UI.WebControls.Button Btn_Report;
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected BEGDC.CC.Web.UserControls.EBD.EBDCtrl EBDCtrl;
        protected System.Web.UI.WebControls.Button Btn_Save;
        protected System.Web.UI.WebControls.Button Btn_Submit;
        protected BEGDC.CC.Web.Control.UserSearchControl AssignCODStaff;
        protected System.Web.UI.WebControls.Label Ctl_CODStaff;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.Button Btn_Check;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.HtmlControls.HtmlTableRow TR_title;
        protected System.Web.UI.WebControls.Button Btn_Reject;
        protected System.Web.UI.WebControls.Button Btn_Reply;
        protected BEGDC.CC.Web.Common.StampCtrl StampCtrl1;
        protected System.Web.UI.WebControls.Button Btn_Query;
        protected BEGDC.CC.Web.UserControls.CV.CVPrintCtrl cvPrintCtrl;
        bool isReadOnly = false;
        protected System.Web.UI.HtmlControls.HtmlInputHidden hiddenScrollHight;
        bool saveBeforeSubmit = false;//joan 2008/8/23
        #endregion

        #region Properties
        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }
        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {
                base.PreInitForm();

                this.Btn_Submit.Attributes.Add("onclick", "javascript:OpenAssignPane(" + Request.QueryString["AppID"] + ");");
                //this.Btn_Check.Attributes.Add("onclick", "javascript:OnCheck();");
                this.Btn_Check.Attributes.Add("onclick", "javascript:OnCheck(" + Request.QueryString["AppID"] + ");");
                this.Btn_Reject.Attributes.Add("onclick", "javascript:OpenCommentPane();");
                this.Btn_Reply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["FlowID"] + ");");
                this.Btn_Query.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["AppID"] + ");");
                InitForm();
            }
            ButtonStatusSetting();
            HideReportButton();
        }

        #region ControlStatusSetting
        private void ControlStatusSetting(Accessibility access)
        {
            if (access == Accessibility.Readonly)
            {
                this.DisableChildrenControls(this);
                //this.stampCtrl1.Visible = false;
            }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            long flowId = this.LoadApplication();

            if (this.Application != null)
            {
                if (this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = " Application No: " + this.Application.AppNo;

                EBDCtrl.isCoveredPerson = !this.Application.IsTransition;
                EBDCtrl.isReadOnly = isReadOnly;
                EBDCtrl.DisableEditEBD();
            }
            else
            {
                WebUtility.Go2ErrorPage(this.Page, "wrong Application ID");
            }
        }
        #endregion

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Reply.Click += new EventHandler(this.Btn_Reply_Click);
            this.Btn_Query.Click += new EventHandler(this.Btn_Query_Click);
            this.Btn_Reject.Click += new EventHandler(this.Btn_Reject_Click);
            this.Btn_Save.Click += new EventHandler(this.Btn_Save_Click);
            this.Btn_Submit.Click += new EventHandler(this.Btn_Submit_Click);
            this.Btn_Check.Click += new EventHandler(this.Btn_Check_Click);
            this.Btn_Report.Click += new EventHandler(Btn_Report_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        #region BuildObjects

        private DataTable BuildSessionTable(string SessionName)
        {
            DataTable dataTable = null;
            object SessDataTable = Session[SessionName];
            if (SessDataTable != null)
            {
                dataTable = (DataTable)SessDataTable;
            }
            return dataTable;
        }

        private IList BindCODStaff(bool isCheck)
        {
            IUser UserService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            IUtility UtilityService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;

            BEGDC.CC.Entity.FlowMember member = null;
            IList list = UtilityService.GetMember(this.AppID, BEGDC.CC.BL.Workflow.UserRole.EBDCRStaff);
            try
            {
                if (!isCheck)
                {
                    //string EmployeeID = this.tbOperationContent.Text;
                    string temp = this.tbOperationContent.Text;
                    string EmployeeID = temp.Substring(0, temp.IndexOf("_"));

                    if (EmployeeID == string.Empty || EmployeeID == "")
                    {
                        return null;
                    }

                    //list =  UtilityService.GetMember(this.AppID, BEGDC.CC.BL.Workflow.UserRole.CRCODStaff);
                    if (list != null && list.Count > 0)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            member = list[i] as BEGDC.CC.Entity.FlowMember;
                            int typeId = UtilityService.GetDicItemID(WorkflowTypes.EBD, BEGDC.CC.BL.Common.DicType.Application_Type);
                            //member.Step = UtilityService.QueryStepByCode(WorkTransition.CR_CheckApp, typeId);
                            member.Employee = UserService.GetUserByID(EmployeeID);
                            //member.Role = UserService.GetRole(BEGDC.CC.BL.Workflow.UserRole.EBDStaff);
                        }
                    }
                }
                else
                {
                    Employee CurrentRequestor = UserService.GetUser(HttpContext.Current.User.Identity.Name);
                    if (list != null && list.Count > 0)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            member = list[i] as BEGDC.CC.Entity.FlowMember;
                            //int typeId = UtilityService.GetDicItemID(WorkflowTypes.CR, BEGDC.CC.BL.Common.DicType.Application_Type);
                            //if(member.Step.StepName == WorkTransition.CR_CloseApp)
                            //{
                            member.Employee = UserService.GetUserByID(CurrentRequestor.Id);
                            //member.Role = UserService.GetRole(BEGDC.CC.BL.Workflow.UserRole.CRCODMgr);
                            //}
                        }
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region Save
        private void Btn_Save_Click(object sender, EventArgs e)
        {
            string url = string.Empty + Request.Form["tbURL"];
            string script = "<script>";
            try
            {
                ImplementSave();

                if (url == string.Empty)
                    script += "VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                if (url != string.Empty)
                {
                    script += "window.location.href='" + url + "'";
                }
                script += "</script>";


            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
            if (!this.saveBeforeSubmit)
            {
                Page.RegisterClientScriptBlock("", script);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');</script>");
            }
        }

        private void ImplementSave()
        {
            try
            {
                //OBTAIN BASIC INFORMATION
                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                BEGDC.CC.Entity.Application App = EBDService.GetApplication(this.AppID);
                //IList CODStaff = BindCODStaff(false);

                Application app = new Application();
                if (this.Application != null)
                {
                    app.Id = this.AppID;
                    app.AppNo = this.Application.AppNo;
                    app.IsTransition = this.Application.IsTransition;
                    app.NeedEVPApproval = this.Application.NeedEVPApproval;
                    app.DepartmentType = this.Application.DepartmentType;
                    app.DepartmentName = this.Application.DepartmentName;
                }

                CustomerInfo customer = new CustomerInfo();
                BusinessPurpose business = new BusinessPurpose();
                Topic topic = new Topic();
                SalesTeamInfo salesTeam = new SalesTeamInfo();
                LogisticalInfo logist = new LogisticalInfo();
                PaymentInfo payment = new PaymentInfo();
                IList customerAttendee = new ArrayList();
                IList alAttendee = new ArrayList();
                IList site = new ArrayList();
                IList cost = new ArrayList();
                IList contract = new ArrayList();
                //update Jovi
                DataTable HotelTable = null;
                DataTable CompanyCarTable = null;
                DataTable LeaseCarTable = null;

                EBDCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                EBDService.SaveEZVisitAssignApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, false, true);
                //EBDService.SaveEZVisitAssignApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost,contract,HotelTable, CompanyCarTable, LeaseCarTable,false, true,CODStaff);

                this.AppID = app.Id;
                this.Application = app;
                EBDCtrl.CustomerID = customer.Id;
                EBDCtrl.TopicID = topic.Id;
                EBDCtrl.SalesTeamID = salesTeam.Id;
                EBDCtrl.LogistID = logist.Id;
                EBDCtrl.BusinessID = business.Id;
                EBDCtrl.PaymentID = payment.Id;
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Submit
        private void Btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                //<--joan 2008/8/23
                string msg;
                this.saveBeforeSubmit = true;
                this.Btn_Save_Click(this.Btn_Save, null);
                this.saveBeforeSubmit = false;
                msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID);
                //-->end
                if (msg != "" && msg != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }

                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                BEGDC.CC.Entity.Application App = EBDService.GetApplication(this.AppID);

                if (this.tbOperationFlag.Text == "assignment")
                {
                    string temp = this.tbOperationContent.Text;
                    string needEVP = temp.Substring(temp.IndexOf("_") + 1);

                    IList CODStaff = BindCODStaff(false);

                    if (CODStaff == null)
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Please assign OCO staff');</script>");
                        return;
                    }

                    Application app = new Application();
                    if (this.Application != null)
                    {
                        app.Id = this.AppID;
                        app.AppNo = this.Application.AppNo;
                        app.IsTransition = this.Application.IsTransition;
                        app.NeedEVPApproval = this.Application.NeedEVPApproval;
                        app.DepartmentType = this.Application.DepartmentType;
                        app.DepartmentName = this.Application.DepartmentName;
                    }

                    CustomerInfo customer = new CustomerInfo();
                    BusinessPurpose business = new BusinessPurpose();
                    Topic topic = new Topic();
                    SalesTeamInfo salesTeam = new SalesTeamInfo();
                    LogisticalInfo logist = new LogisticalInfo();
                    PaymentInfo payment = new PaymentInfo();
                    IList customerAttendee = new ArrayList();
                    IList alAttendee = new ArrayList();
                    IList site = new ArrayList();
                    IList cost = new ArrayList();
                    IList contract = new ArrayList();
                    //update Jovi
                    DataTable HotelTable = null;
                    DataTable CompanyCarTable = null;
                    DataTable LeaseCarTable = null;

                    EBDCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);

                    if (needEVP.ToUpper() == "YES")
                        app.NeedEVPApproval = true;
                    else
                        app.NeedEVPApproval = false;

                    EBDService.SubmitEZVisitAssignApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, true, tbComment.Text, CODStaff);
                }

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Reject
        private void Btn_Reject_Click(object sender, EventArgs e)
        {
            try
            {
                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                //BEGDC.CC.Entity.Application App = EBDService.GetApplication(this.AppID);
                EBDService.RejectAssignApplication(Convert.ToInt64(Request.QueryString["FlowID"]), WorkTransition.Reject, WebUtility.DeCodeString(Server, tbComment.Text));

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
        }
        #endregion

        #region Check
        private void Btn_Check_Click(object sender, EventArgs e)
        {
            try
            {
                //<--joan 2008/8/23
                string msg;
                this.saveBeforeSubmit = true;
                this.Btn_Save_Click(this.Btn_Save, null);
                this.saveBeforeSubmit = false;
                msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID);
                //-->end
                if (msg != "" && msg != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }

                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                BEGDC.CC.Entity.Application App = EBDService.GetApplication(this.AppID);

                if (this.tbOperationFlag.Text == "check" || !this.Application.IsSSME)
                {
                    string temp = this.tbOperationContent.Text;
                    string needEVP = temp.Substring(temp.IndexOf("_") + 1);

                    IList CODStaff = BindCODStaff(true);

                    Application app = new Application();
                    if (this.Application != null)
                    {
                        app.Id = this.AppID;
                        app.AppNo = this.Application.AppNo;
                        app.IsTransition = this.Application.IsTransition;
                        app.NeedEVPApproval = this.Application.NeedEVPApproval;
                        app.DepartmentType = this.Application.DepartmentType;
                        app.DepartmentName = this.Application.DepartmentName;
                    }
                    CustomerInfo customer = new CustomerInfo();
                    BusinessPurpose business = new BusinessPurpose();
                    Topic topic = new Topic();
                    SalesTeamInfo salesTeam = new SalesTeamInfo();
                    LogisticalInfo logist = new LogisticalInfo();
                    PaymentInfo payment = new PaymentInfo();
                    IList customerAttendee = new ArrayList();
                    IList alAttendee = new ArrayList();
                    IList site = new ArrayList();
                    IList cost = new ArrayList();
                    IList contract = new ArrayList();
                    //update Jovi
                    DataTable HotelTable = null;
                    DataTable CompanyCarTable = null;
                    DataTable LeaseCarTable = null;

                    EBDCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);

                    if (needEVP.ToUpper() == "YES")
                        app.NeedEVPApproval = true;
                    else
                        app.NeedEVPApproval = false;

                    EBDService.SubmitEZVisitAssignCheckApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, CODStaff, true, tbComment.Text);
                }
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Export
        private void Btn_Export_Click(object sender, EventArgs e)
        {
            try
            {
                ExcelTool.ICCExcelExport excelExport;
                if (this.Application.IsTransition)
                    excelExport = new ExcelTool.ExportCRFormA();
                else
                    excelExport = new ExcelTool.ExportCRFormB();
                excelExport.Export(this.Page, this.AppID);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
            }
        }
        #endregion

        #region ButtonStatusSetting
        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.Btn_Save.Visible = this.Access.IsButtonVisible(EBDTransitionList.Save);
            this.Btn_Submit.Visible = this.Access.IsButtonVisible(EBDTransitionList.Assign);
            this.Btn_Check.Visible = this.Access.IsButtonVisible(EBDTransitionList.Check);
            this.Btn_Reject.Visible = this.Access.IsButtonVisible(EBDTransitionList.Reject);
            this.Btn_Reply.Visible = this.Access.IsButtonVisible(EBDTransitionList.Reply);
            this.Btn_Query.Visible = this.Access.IsButtonVisible(EBDTransitionList.Query);
            this.cvPrintCtrl.ProcessType = WorkflowTypes.EBD;
            this.cvPrintCtrl.Visible = this.Access.IsButtonVisible(EBDTransitionList.Copy);

            if ((this.Access.IsReadOnly || this.IsView))
                isReadOnly = true;
        }
        #endregion

        #region Reply
        private void Btn_Reply_Click(object sender, EventArgs e)
        {
            try
            {
                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;

                ImplementSave();

                EBDService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Query
        private void Btn_Query_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag.Text == "query")
                {
                    IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                    EBDService.Query(Convert.ToInt64(Request.QueryString["FlowID"]), this.tbOperationContent.Text, Session["Comment"].ToString());

                    Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
                }
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM002 + "');window.close();</script>");
            }
        }
        #endregion

        void Btn_Report_Click(object sender, EventArgs e)
        {
            try
            {
                IEBD EBDService = AppContainer.Instance[ServiceConst.EBDService] as IEBD;
                EBDService.ReportToEmployeeApproved(this.Application);
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                if (exp.InnerException != null)
                    Page.RegisterClientScriptBlock("", "<script>alert('" + exp.InnerException.Message + "');</script>");
                else
                    Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }

        private void HideReportButton()
        {
            BEGDC.CC.BL.Workflow.CCIdentity identity = (BEGDC.CC.BL.Workflow.CCIdentity)this.Page.User.Identity;
            //当前用户是否拥有EBDCRMgr
            IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            if (userService.IsInRole(identity.UserInfo.NameEN, BEGDC.CC.BL.Workflow.UserRole.EBDCRMgr))
            {
                this.Btn_Report.Visible = false;
            }
            else
            {
                if (this.Application.RequesterNo.ReportTo != null && string.Equals(this.Application.RequesterNo.ReportTo.Id, identity.UserInfo.Id))
                {
                    this.Btn_Report.Visible = true;
                    this.Btn_Reply.Visible = false;
                    this.Btn_Submit.Visible = false;
                    this.Btn_Check.Visible = false;
                    this.Btn_Save.Visible = false;
                }
                else
                {
                    this.Btn_Report.Visible = false;
                }
            }
        }
    }
}
